(function () {

    "use strict";

    var popup = new auiPopup();

    var api = {
        getDetailUrl: '/api/order/detail',
        getExpressUrl: '/api/order/shipping',
        submitOrder: '/api/order/add',
        getTicketUrl: '/api/ticket/getTicketList',
        afterPay: '/api/order/afterPay'
    };
    sm.controller('wx-order-confirm-controller', ['$scope', '$http', 'Modal', 'Toast', function ($scope, $http, Modal, Toast){

        $scope.canuse = 0;
        $scope.canotuse = 0;
        $scope.goods = [];
        $scope.address = {};
        $scope.total = 0;               // 商品价格
        $scope.totalFormat = 0;         // 格式化的商品价格
        $scope.expressTotal = 0;        // 物流费用
        $scope.expressTotalFormat = 0;  // 格式化的物流费用
        $scope.totalPrice = 0;          // 商品总价
        $scope.totalPriceFormat = 0;
        $scope.expressConfig = {};
        $scope.message = '';
        $scope.isSubmitting = false;
        $scope.showAddAddress = false;
        $scope.tickets = [];
        $scope.selectedTicket = {};
        $scope.nowType = 'canuse';
        $scope.userInfo = {};
        $scope.orderId = 0;
        $scope.usemoney = {
            isUse: false,
            amount: '',
            amount_format: '',
            showError: false,
            msg: ''
        };

        var search = window.location.search;
        var addressId = search.split('=')[1];

        // 物流配置
        $http.get(api.getExpressUrl).then(function (config) {
            if (config.data.state) {

                $http.get(api.getTicketUrl, {
                    params: {
                        page: 1,
                        type: "nouse"
                    }
                }).success(function (res) {
                    if (res.state) {
                        $scope.tickets = res.data;
                    }
                });

                $scope.expressConfig = config.data.data;
                $http.get(api.getDetailUrl, {
                    params: {
                        addressId: !addressId ? 0 : addressId
                    }
                }).success(function (res) {
                    if (res.state) {
                        var data = res.data;
                        if (!data.address.id) {
                            $scope.showAddAddress = true;
                        } else {
                            var addr = data.address;
                            $scope.address = addr;
                            $scope.address['detail'] = addr.province + ' ' + addr.city + ' ' + addr.area + ' ' + addr.address;
                        }

                        if (data.goods) {
                            $scope.goods = data.goods;
                        }

                        $scope.calcPrice();
                        // $scope.calcExpressPrice();
                        $scope.expressTotal = data.exp.total || 0;
                        $scope.expressTotalFormat = parseFloat(data.exp.total / 100).toFixed(2);

                        $scope.totalPrice = accAdd($scope.expressTotal, $scope.total);
                        $scope.totalPriceFormat = (accAdd($scope.expressTotal, $scope.total) / 100).toFixed(2);
                        $scope.userInfo = res.data.user;
                    } else {
                        Toast.error({title: '加载失败'});
                    }
                });

            }
        });

        /**
         * 计算商品价格
         */
        $scope.calcPrice = function () {
            var sum = 0, counter = 0;
            angular.forEach($scope.goods, function (val) {
                counter++;
                var s = 0;
                s = accMul(parseInt(val['num']), val['price']);
                sum = accAdd(sum, s);
            });

            $scope.total = sum;
            $scope.totalFormat = (sum / 100).toFixed(2);
        };

        // 计算价格
        $scope.calcExpressPrice = function() {
            var totalAmount = 0, totalWeight = 0;
            angular.forEach($scope.goods, function (val) {

                var s = 0;

                // check type
                if (val['expType'] == 1) {
                    // 按重量
                    if ($scope.expressConfig.payer != 'buyer') {
                        totalWeight = 0;
                    } else {
                        // 总重量
                        var t = accMul(val['num'], parseFloat(val['expressWeight']));
                        totalWeight = accAdd(totalWeight, t);
                    }
                } else {
                    // 一口价
                    s = accMul(val['num'], val['expAmount']);
                }

                totalAmount = accAdd(totalAmount, s);
            });

            if (totalWeight == 0) {
                $scope.expressTotal = totalAmount;
                $scope.expressTotalFormat = parseFloat(totalAmount / 100).toFixed(2);
                return true;
            }

            var costs = $scope.expressConfig.costs;
            if (totalWeight < costs.firstWeight) {
                // 价格换算成分
                $scope.expressTotal = parseInt(costs.firstCost * 100) + totalAmount;
                $scope.expressTotalFormat = parseFloat($scope.expressTotal / 100).toFixed(2);
                return true;
            }

            // 计算物流费用
            var left = accSubtr(totalWeight, costs.firstWeight);
            var price = Math.ceil(accDiv(left, costs.incrWeight));
            var wTotal = accAdd(accMul(price, costs.incrCost * 100), costs.firstCost * 100);
            $scope.expressTotal = accAdd(wTotal, totalAmount);
            $scope.expressTotalFormat = parseFloat(accAdd(wTotal, totalAmount) / 100).toFixed(2);
        };

        $scope.setNowType = function (t) {
            $scope.nowType = t;
        };

        /**
         * 使用余额
         * @returns {boolean}
         */
        $scope.useAmount = function () {

            var amount = parseInt($scope.usemoney.amount_text * 100);
            if (amount > $scope.userInfo.amount) {
                $scope.usemoney.isUse = false;
                $scope.usemoney.showError = true;
                $scope.usemoney.msg = '可用余额不足';
                return false;
            }
            else if (amount < 0) {
                $scope.usemoney.isUse = false;
                $scope.usemoney.showError = true;
                $scope.usemoney.msg = '金额不能为负数';
                return false;
            }
            else if (amount == 0) {
                $scope.usemoney.isUse = false;
                $scope.usemoney.amount = 0;
                $scope.usemoney.amount_format = (amount / 100).toFixed(2);
            }
            else {
                $scope.usemoney.isUse = true;
                $scope.usemoney.amount = amount;
                $scope.usemoney.amount_format = (amount / 100).toFixed(2);

                var totalPrice = accSubtr($scope.totalPrice, $scope.usemoney.amount);
                if (totalPrice < 0 ) {
                    $scope.usemoney.isUse = false;
                    $scope.usemoney.showError = true;
                    $scope.usemoney.msg = '所选金额超过订单总金额';
                    return false;
                }

                $scope.totalPrice = totalPrice;
                $scope.totalPriceFormat = ($scope.totalPrice / 100).toFixed(2);
            }

            popup.hide();
        };

        // 可用余额检查
        $scope.$watch('usemoney.amount_text', function (newval, oldval) {
            if (newval === oldval) {
                return false;
            }

            var amount = parseInt($scope.usemoney.amount_text * 100);
            if (amount > $scope.userInfo.amountUnLimit) {
                $scope.usemoney.isUse = false;
                $scope.usemoney.showError = true;
                $scope.usemoney.msg = '可用余额不足';
                return false;
            }
            else if (amount < 0) {
                $scope.usemoney.isUse = false;
                $scope.usemoney.showError = true;
                $scope.usemoney.msg = '金额不能为负数';
            }
            else {
                $scope.usemoney.showError = false;
                $scope.usemoney.msg = '';
            }
            $scope.usemoney.amount = amount;
        });

        /**
         * 提交订单
         */
        $scope.add = function() {

            var ticketPrice, ticketId = 0, useAmount = 0;
            if ($scope.selectedTicket.id) {
                ticketPrice = $scope.selectedTicket.amount;
                ticketId = $scope.selectedTicket.id;
            }

            if ($scope.usemoney.isUse) {
                useAmount = $scope.usemoney.amount;
            }

            var data = {
                'expressId': $scope.address.id,             // 收货地址
                'message': $scope.message,                  // 买家留言
                'goodsPrice': $scope.total,                 // 商品总价
                'expressPrice': $scope.expressTotal,        // 物流费用
                'ticketPrice': ticketPrice,                 // 优惠券
                'ticketId': ticketId,                       // 优惠券ID
                'useBalance': useAmount,                    // 是否使用余额
                'totalPrice': $scope.totalPrice             // 总价
            };

            if (!data.expressId) {
                Modal.alert({
                    title: '操作提示',
                    content: '收货地址不能为空'
                });
                return false;
            }

            $scope.isSubmitting = true;
            Toast.loading({title: '提交订单'});
            $http.post(api.submitOrder, data).success(function (res) {
                $scope.isSubmitting = false;
                Toast.stop();
                if (res.state) {
                    if (!res.data.needPay) {
                        location.href = '/order';
                        return true;
                    }

                    var result = res.data;
                    var data = result.jssdk;
                    $scope.orderId = result.order;
                    wx.chooseWXPay({
                        timestamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.package,
                        signType: 'MD5',
                        paySign: data.paySign,
                        success: function (res) {
                            afterPay(result.order, res);
                        }
                    });
                } else {
                    var error = res.error ? res.error : '下单失败';
                    Toast.error({'title': error});
                }
            });
        };

        function afterPay (orderId, data) {
            $http.post(api.afterPay, {
                'orderId': $scope.order.orderId,
                'status': 'success'
            }).success(function (res) {
                if (res.state) {
                    location.href="/order";
                } else {
                    Modal.alert({
                        title: '操作提示',
                        content: '订单存在异常,请联系客服!'
                    });
                }
            });
        }

        /**
         * 选择地址
         */
        $scope.selectAddr = function () {
            if ($scope.address) {
                // 选择
                location.href = '/address/select';
            } else {
                // 添加
                location.href = '/address/add?s=confirm';
            }
        };

        $scope.alertCash = function () {
            popup.show(document.getElementById("lessAmount"));
        };


        // 使用优惠券弹出页面
        $scope.alertPop = function () {
            $scope.canuse = 0;
            $scope.canotuse = 0;
            angular.forEach($scope.tickets, function (val) {
                if (parseInt(val['limit_amount']) > $scope.total) {
                    val.canuse = false
                    $scope.canotuse += 1;
                } else {
                    val.canuse = true;
                    $scope.canuse += 1;
                }
            });
            popup.show(document.getElementById("bottom"))
        };

        /**
         * 确认
         */
        $scope.confirmTicket = function () {
            angular.forEach($scope.tickets, function(val) {
                if (val.selected) {
                    var totalPrice = accSubtr($scope.totalPrice, parseInt(val.amount));
                    $scope.totalPrice = totalPrice;
                    $scope.totalPriceFormat = ($scope.totalPrice / 100).toFixed(2);
                    $scope.selectedTicket = val
                }
            });
            popup.hide();
        };

        /**
         * 选择
         * @param item
         */
        $scope.selectTicket = function (item) {
            angular.forEach($scope.tickets, function (val) {
                val.selected = false;
            });
            item.selected = true;
        };

        /**
         * 除法
         * @param arg1
         * @param arg2
         * @returns {number}
         */
        function accDiv(arg1,arg2){
            var t1=0,t2=0,r1,r2;
            try{t1=arg1.toString().split(".")[1].length}catch(e){}
            try{t2=arg2.toString().split(".")[1].length}catch(e){}
            r1=Number(arg1.toString().replace(".",""))
            r2=Number(arg2.toString().replace(".",""))
            return (r1/r2) * Math.pow(10,t2-t1);
        }

        /**
         * 乘法函数，用来得到精确的乘法结果
         * 说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
         * @param arg1
         * @param arg2
         * @returns {number}
         */
        function accMul(arg1,arg2)
        {
            var m=0,s1=arg1.toString(),s2=arg2.toString();
            try{m+=s1.split(".")[1].length}catch(e){}
            try{m+=s2.split(".")[1].length}catch(e){}
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
        }

        /**
         * 加法
         * @param arg1
         * @param arg2
         * @returns {number}
         */
        function accAdd(arg1,arg2){
            var r1,r2,m;
            try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
            try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2))
            return (arg1*m+arg2*m)/m
        }

        /**
         * 减法
         * @param arg1
         * @param arg2
         * @returns {string}
         */
        function accSubtr(arg1,arg2){
            var r1,r2,m,n;
            try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
            try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
            m=Math.pow(10,Math.max(r1,r2));

            //动态控制精度长度
            n=(r1>=r2)?r1:r2;
            return ((arg1*m-arg2*m)/m).toFixed(n);
        }

    }]);
})();

